<?php
/**
 * Created by PhpStorm.
 * User: sh01
 * Date: 2017/12/23
 * Time: 10:56
 */

namespace app;


class Client
{
    public function request()
    {
        error_reporting(E_ALL);
        set_time_limit(0);
        echo '1--client start TCP/IP connection'."\r\n";

        $port = 1935;
        $ip = "127.0.0.1";
        /**
         * 10  +-------------------------------
         * 11  *    @socket连接整个过程
         * 12  +-------------------------------
         * 13  *    @socket_create
         * 14  *    @socket_connect
         * 15  *    @socket_write
         * 16  *    @socket_read
         * 17  *    @socket_close
         * 18  +--------------------------------
         * 19  */

        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($socket < 0) {
            echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
        } else {
            echo "2--client create socket object success. \n";
        }
        
        $result = socket_connect($socket, $ip, $port);
        if (!$result) {
            echo "socket_connect() failed.\n Reason: ($result) " . socket_strerror($result) . "\n";
            die('connect fail');
        } else {
            echo "3--client  connect to :[ '$ip' ] - port :[ '$port' ]......... success \r\n";
        }

        $in = "Ho , First blood";
        $out = '';

        if (!socket_write($socket, $in, strlen($in))) {
            echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
        } else {
            echo "4--client send [$in] to Socket Server success ! \n";
        }

        while ($out = socket_read($socket, 8192)) {
            echo "5--client receive response [ $out ] from server success !\n";
        }
        socket_close($socket);
        echo "6--client Close SOCKET...\n";
    }
}

$client = new Client();
$client->request();